package com.valuedaas.schoolsafety.controller.user;

import com.valuedaas.schoolsafety.common.Constants;
import com.valuedaas.schoolsafety.common.base.Result;
import com.valuedaas.schoolsafety.common.collects.OrgUnit;
import com.valuedaas.schoolsafety.common.enums.DataStatus;
import com.valuedaas.schoolsafety.common.enums.UserState;
import com.valuedaas.schoolsafety.controller.user.vo.User;
import com.valuedaas.schoolsafety.service.organization.OrgService;
import com.valuedaas.schoolsafety.service.user.UserService;
import com.valuedaas.schoolsafety.util.SecurityUtil;
import com.valuedaas.schoolsafety.util.WebUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping(value = "/user", produces = {"application/json;charset=utf-8"})
@Api(description = "用户管理", value = "UserController")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private OrgService orgService;

    @GetMapping("/signin")
    @ApiOperation(value = "登录", notes = "登录")
    public String login(@RequestParam(required = true) String username, @RequestParam(required = true) String password,
                        @RequestParam(required = false) boolean remember,
                        @RequestParam(required = false, defaultValue = "7") int remberDays) {
        User user = userService.login(username, password);
        if (user == null) {
            return Result.error("您的用户名或者密码错误", null);
        }
        if (!(user.getState() == UserState.PASS)) {
            return Result.error("用户状态异常", null);
        }
        if (StringUtils.isNotEmpty(user.getUnitId())) {
            Document orgDoc = orgService.get(user.getUnitId());
            if (orgDoc == null) {
                return Result.error("用户所属单位不存在", null);
            }
            user.setUnitName(orgDoc.getString(OrgUnit.NAME));
        }
        HttpServletRequest request = WebUtil.getRequest();
        request.getSession().invalidate();
        RequestContextHolder.getRequestAttributes().setAttribute(Constants.SESSION_KEY, user,
                RequestAttributes.SCOPE_SESSION);
        // 处理记住我
        if (remember) {
            WebUtil.rememberMe(user, password, remberDays);
        }
        return Result.ok("登录成功", user);
    }


}

